﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Http;
using System.Threading;
using Common.Logging;
 
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using Rmq.Center;
using User.Api.BizExtensions;
using User.Api.Helpers;
using User.Api.HttpClients;

namespace Out.TaskRunner.RmqWorkers
{
    public class OrderPickupingWorker : IWorker
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(OrderPickupingWorker));

        public void Start(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            using (var consumer = new OrderPickupingConsumer())
            {
                consumer.Subscribe((id, count, dt, msg, channel) =>
                {
                    if (msg.OrderType == OrderType.挂号订单)
                    {
                        return ProcessRegOrder(msg.OrderId, channel);
                    }
                    else if (msg.OrderType == OrderType.门诊缴费订单)
                    {
                        return ProcessBillOrder(msg.OrderId, channel);
                    }
                 

                    return new ConsumedResult { Ack = true };
                });

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }

                    Thread.Sleep(500);
                }
            }
        }

        private ConsumedResult ProcessRegOrder(int orderId, WrapperChannel channel)
        {
            OrderSummary order;
            using (var ctx = new HzfyWeiXinEntities())
            {
                order = ctx.ApptOrder.Where(x => x.Id == orderId)
                    .Select(x => new OrderSummary
                    {
                        Id = x.Id,
                        OrderType = x.OrderType,
                        CardNo = x.CardNo,
                        OrderStatus = x.OrderStatus,
                        OrderNo = x.OrderNo,
                        SumFee = x.SumFee,
                        WxTransactionId = x.WxTransactionId,
                        PayTime = x.PayTime,
                        WxUserId = x.WxUserId,
                        DeptId = x.DeptId,
                        RegDate = x.RegDate,
                        TimeSlice = x.TimeSlice,
                        RegType = x.RegType,
                        TreatFee = x.TreatFee,
                        Fee = x.Fee,
                        RegNo = x.RegNo,
                        StartTime = x.StartTime,
                        EndTime = x.EndTime,
                        OtherFee = x.OtherFee,
                        DoctorId = x.DoctorId,
                        DeptName =  x.DeptName,
                        DoctorName = x.DoctorName
                    }).FirstOrDefault();
                if (order == null)
                {
                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }
            }

            var apptOrderType = order.OrderType;

                // 预约订单
                if (apptOrderType == ApptOrderExtensions.OrderType.预约.ToInt32().ToString())
                {
                // 取号中
                //order.OrderStatus = ApptOrderExtensions.OrderStatus.取号中.ToInt32();
                //ctx.SaveChanges();
                using (var _ctx = new HzfyWeiXinEntities())
                {
                    SqlParameter[] para =
                    {
                                new SqlParameter("@OrderStatus", ApptOrderExtensions.OrderStatus.取号中.ToInt32()),
                                new SqlParameter("@OrderId", order.Id),
                            };
                    _ctx.Database.ExecuteSqlCommand(
                        "Update ApptOrder set OrderStatus= @OrderStatus where Id=@OrderId", para);
                }
                #region 不需要
                //var request = new Request4ExeRegister();
                //request.OrderId = order.OrderNo;
                //request.PayType = "0";
                //request.CardNo = order.CardNo;
                //request.PayCount = order.SumFee.ToString();
                //request.TransNo = order.WxTransactionId;
                //request.TransTime = order.PayTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");

                //Response4ExeRegister regResponse;
                //try
                //{
                //    var httpClient = InHttpClient.GetClient();
                //    var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/ExeRegister", request).Result;
                //    responseMsg.EnsureSuccessStatusCode();
                //    regResponse = responseMsg.Content.ReadAsAsync<Response4ExeRegister>().Result;
                //}
                //catch (Exception ex)
                //{
                //    Logger.ErrorFormat("调用院内取号Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                //    // RMQ 执行取号结果查询
                //    var pickupingChkProducer = new OrderPickupingChkProducer();
                //    pickupingChkProducer.Publish(new OrderPickupingChkMsg
                //    {
                //        OrderType = Rmq.Center.OrderType.挂号订单,
                //        OrderId = order.Id
                //    });

                //    return new ConsumedResult
                //    {
                //        Ack = true
                //    };
                //}

                //if (regResponse.ResultCode != "0")
                //{
                //    // 取号失败
                //    //order.OrderStatus = ApptOrderExtensions.OrderStatus.取号失败.ToInt32();
                //    //order.Remark = regResponse.ResultDesc;
                //    //ctx.SaveChanges();

                //    using (var _ctx = new HzfyWeiXinEntities())
                //    {
                //        SqlParameter[] para =
                //        {
                //            new SqlParameter("@OrderStatus", ApptOrderExtensions.OrderStatus.取号失败.ToInt32()),
                //            new SqlParameter("@Remark", regResponse.ResultDesc),
                //            new SqlParameter("@OrderId", order.Id),
                //        };
                //        _ctx.Database.ExecuteSqlCommand(
                //            "Update ApptOrder set OrderStatus= @OrderStatus,Remark=@Remark where Id=@OrderId", para);
                //    }

                //    // RMQ 取消预约 
                //    //var unapptingProducer = new OrderUnapptingProducer();
                //    //    unapptingProducer.Publish(new OrderUnapptingMsg
                //    //    {
                //    //        OrderType = Rmq.Center.OrderType.挂号订单,
                //    //        OrderId = order.Id,
                //    //        Reason = 2
                //    //    });

                //    // RMQ 执行取消锁号操作
                //    var unlockingProducer = new OrderUnlockingProducer();
                //    unlockingProducer.Publish(new OrderUnlockingMsg
                //    {
                //        OrderType = OrderType.挂号订单,
                //        OrderId = orderId
                //    });

                //    // RMQ 发送用户挂号失败通知
                //    var msgProducer = new UserMessageProducer();
                //    msgProducer.Publish(new UserMessageMsg
                //    {
                //        Type = UserMessageType.挂号失败通知,
                //        OrderId = order.Id
                //    });

                //    // RMQ 执行退费操作
                //    if (order.SumFee > 0)
                //    {
                //        var refundingProducer = new OrderRefundingPickupFailedProducer();
                //        refundingProducer.Publish(new OrderRefundingPickupFailedMsg
                //        {
                //            OrderType = OrderType.挂号订单,
                //            OrderId = order.Id
                //        });
                //    }
                //}
                //else
                //{
                //    // 取号成功
                //    //order.OrderStatus = ApptOrderExtensions.OrderStatus.取号成功.ToInt32();
                //    //order.FetchTime = DateTime.Now;
                //    //order.RegNo = regResponse.RegNo;
                //    //order.SuggestBeginTime = regResponse.BeginTime;
                //    //order.SuggestEndTime = regResponse.EndTime;
                //    //order.Location = regResponse.Address;
                //    //order.VisitNo = regResponse.VisitNo;
                //    //ctx.SaveChanges();
                //    using (var ctx = new HzfyWeiXinEntities())
                //    {
                //        var para = new SqlParameter[]
                //        {
                //        new SqlParameter("@OrderStatus", ApptOrderExtensions.OrderStatus.取号成功.ToInt32()),
                //        new SqlParameter("@RegNo", regResponse.RegNo),
                //        new SqlParameter("@SuggestBeginTime", regResponse.BeginTime),
                //        new SqlParameter("@SuggestEndTime", regResponse.EndTime),
                //        new SqlParameter("@Location", regResponse.Address),
                //        new SqlParameter("@VisitNo", regResponse.VisitNo),
                //        new SqlParameter("@FetchTime", DateTime.Now),
                //        new SqlParameter("@OrderId", order.Id)
                //        };
                //        ctx.Database.ExecuteSqlCommand("Update ApptOrder set OrderStatus= @OrderStatus," +
                //                                       "RegNo = @RegNo,SuggestBeginTime=@SuggestBeginTime," +
                //                                       "SuggestEndTime=@SuggestEndTime,Location=@Location,VisitNo=@VisitNo," +
                //                                       "FetchTime=@FetchTime where Id=@OrderId", para);
                //    }
                //    // RMQ 发送用户挂号成功通知
                //    var messageProducer = new UserMessageProducer();
                //    messageProducer.Publish(new UserMessageMsg
                //    {
                //        Type = UserMessageType.挂号成功通知,
                //        OrderId = order.Id
                //    });

                //    // RMQ 发送发货通知
                //    if (order.SumFee > 0)
                //    {
                //        using (var ctx = new HzfyWeiXinEntities())
                //        {
                //            var wxuser = ctx.WxUser.FirstOrDefault(x => x.Id == order.WxUserId);
                //            if (wxuser != null)
                //            {
                //                //TenpayV2Helper.DoDeliverNotify(wxuser.OpenId, order.WxTransactionId,
                //                //"AP" + order.OrderNo, "1", "");
                //                WeixinPayV3Helper.DoDeliveryNotify(wxuser.OpenId, order.WxTransactionId,
                //                    "AP" + order.OrderNo,
                //                    ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000)
                //                        .ToString(), "1", "");
                //            }
                //        }
                //    }

                //    //#region 用于发送报到通知
                //    //var convertSucceed = false;
                //    //DateTime sendTime = new DateTime();
                //    //DateTime deadLine = new DateTime();
                //    //convertSucceed = System.DateTime.TryParse(order.RegDate + " " + order.StartTime, out sendTime);
                //    //if (convertSucceed)
                //    //    convertSucceed = System.DateTime.TryParse(order.RegDate + " " + order.EndTime, out deadLine);

                //    //if (convertSucceed)
                //    //{
                //    //    using (var ctx = new HzfyWeiXinEntities())
                //    //    {
                //    //        sendTime = sendTime.AddMinutes(-40); //开诊时间前40分钟
                //    //        var signInNotice = new SignInNotice
                //    //        {
                //    //            WxUserId = order.WxUserId,
                //    //            OrderNo = order.OrderNo,
                //    //            DeptName = order.DeptName,
                //    //            DoctorName = order.DoctorName,
                //    //            RegDate = order.RegDate,
                //    //            StartTime = order.StartTime,
                //    //            EndTime = order.EndTime,
                //    //            Status = 0,
                //    //            CardNo = order.CardNo,
                //    //            CreateTime = System.DateTime.Now,
                //    //            IsSended = 0,
                //    //            NeedSendTime = sendTime, //需要发送时间
                //    //            DeadlineToSend = deadLine //最晚发送时间
                //    //        };
                //    //        ctx.SignInNotices.Add(signInNotice);
                //    //        ctx.SaveChanges();
                //    //    }
                //    //}
                //    //#endregion
                //}
                #endregion

                var directRegRequest = new Request4ExeResSourceRegister();
                directRegRequest.OrderId = order.OrderNo;
                directRegRequest.OrderType = "0";
                directRegRequest.PayType = "0";
                directRegRequest.CardNo = order.CardNo;
                directRegRequest.PayCount = order.SumFee.ToString();
                directRegRequest.TransNo = order.WxTransactionId;
                directRegRequest.TransTime = order.PayTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");
                directRegRequest.DeptId = order.DeptId;
                directRegRequest.DoctorId = order.DoctorId;
                directRegRequest.RegDate = order.RegDate;
                directRegRequest.TimeSlice = order.TimeSlice;
                directRegRequest.RegType = order.RegType;
                directRegRequest.StartTime = order.StartTime;
                directRegRequest.EndTime = order.EndTime;
                directRegRequest.Fee = order.Fee.GetValueOrDefault().ToString();
                directRegRequest.TreatFee = order.TreatFee.GetValueOrDefault().ToString();
                directRegRequest.OtherFee = order.OtherFee.GetValueOrDefault().ToString();
                directRegRequest.RegNo = order.RegNo ?? "";

                Response4ExeResSourceRegister directRegResponse;

                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/GetRegInfo", directRegRequest).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    directRegResponse = responseMsg.Content.ReadAsAsync<Response4ExeResSourceRegister>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内直接取号Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    // RMQ 执行取号结果查询
                    var pickupingChkProducer = new OrderPickupingChkProducer();
                    pickupingChkProducer.Publish(new OrderPickupingChkMsg
                    {
                        OrderType = Rmq.Center.OrderType.挂号订单,
                        OrderId = order.Id
                    },5 * 60 * 1000);

                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }

                if (directRegResponse.ResultCode != "0")
                {
                    // 取号失败
                    //order.OrderStatus = ApptOrderExtensions.OrderStatus.取号失败.ToInt32();
                    //order.Remark = directRegResponse.ResultDesc;
                    //ctx.SaveChanges();
                    using (var _ctx = new HzfyWeiXinEntities())
                    {
                        SqlParameter[] para =
                        {
                                new SqlParameter("@OrderStatus", ApptOrderExtensions.OrderStatus.取号失败.ToInt32()),
                                new SqlParameter("@Remark", directRegResponse.ResultDesc),
                                new SqlParameter("@OrderId", order.Id),
                            };
                        _ctx.Database.ExecuteSqlCommand(
                            "Update ApptOrder set OrderStatus= @OrderStatus,Remark=@Remark where Id=@OrderId", para);
                    }

                    // RMQ 发送用户挂号失败通知
                    var msgProducer = new UserMessageProducer();
                    msgProducer.Publish(new UserMessageMsg
                    {
                        Type = UserMessageType.挂号失败通知,
                        OrderId = order.Id
                    });

                    // RMQ 执行取消锁号操作
                    var unlockingProducer = new OrderUnlockingProducer();
                    unlockingProducer.Publish(new OrderUnlockingMsg
                    {
                        OrderType = OrderType.挂号订单,
                        OrderId = orderId
                    });
                    // RMQ 执行退费操作
                    if (order.SumFee > 0)
                    {
                        var refundingProducer = new OrderRefundingPickupFailedProducer();
                        refundingProducer.Publish(new OrderRefundingPickupFailedMsg
                        {
                            OrderType = OrderType.挂号订单,
                            OrderId = order.Id
                        });
                    }
                }
                else
                {
                    // 取号成功
                    //order.OrderStatus = ApptOrderExtensions.OrderStatus.取号成功.ToInt32();
                    //order.RegNo = directRegResponse.RegNo;
                    //order.SuggestBeginTime = directRegResponse.BeginTime;
                    //order.SuggestEndTime = directRegResponse.EndTime;
                    //order.Location = directRegResponse.Address;
                    //order.VisitNo = directRegResponse.VisitNo;

                    //order.FetchTime = DateTime.Now;
                    //ctx.SaveChanges();
                    using (var ctx = new HzfyWeiXinEntities())
                    {
                        var para = new SqlParameter[]
                        {
                            new SqlParameter("@OrderStatus", ApptOrderExtensions.OrderStatus.取号成功.ToInt32()),
                            new SqlParameter("@RegNo", directRegResponse.RegInfo.RegNo),
                            new SqlParameter("@SuggestBeginTime", directRegResponse.RegInfo.StartTime),
                            new SqlParameter("@SuggestEndTime", directRegResponse.RegInfo.EndTime),
                            new SqlParameter("@Location", directRegResponse.RegInfo.Address),
                            new SqlParameter("@VisitNo", directRegResponse.RegInfo.VisitNo),
                            new SqlParameter("@FetchTime", DateTime.Now),
                            new SqlParameter("@OrderId", order.Id)
                        };
                        ctx.Database.ExecuteSqlCommand("Update ApptOrder set OrderStatus= @OrderStatus," +
                                                       "RegNo = @RegNo,SuggestBeginTime=@SuggestBeginTime," +
                                                       "SuggestEndTime=@SuggestEndTime,Location=@Location,VisitNo=@VisitNo," +
                                                       "FetchTime=@FetchTime where Id=@OrderId", para);
                    }
                    // RMQ 发送用户挂号成功通知
                    var messageProducer = new UserMessageProducer();
                    messageProducer.Publish(new UserMessageMsg
                    {
                        Type = UserMessageType.挂号成功通知,
                        OrderId = order.Id
                    });

                    // RMQ 发送发货通知
                    if (order.SumFee > 0)
                    {
                        using (var ctx = new HzfyWeiXinEntities())
                        {
                            var wxuser = ctx.WxUser.FirstOrDefault(x => x.Id == order.WxUserId);
                            if (wxuser != null)
                            {
                                //TenpayV2Helper.DoDeliverNotify(wxuser.OpenId, order.WxTransactionId,
                                //"AP" + order.OrderNo, "1", "");
                                WeixinPayV3Helper.DoDeliveryNotify(wxuser.OpenId, order.WxTransactionId,
                                    "AP" + order.OrderNo,
                                    ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000)
                                        .ToString(), "1", "");
                            }
                        }
                    }
                }

                return new ConsumedResult
                    {
                        Ack = true
                    };
                }

                // 其他平台预约
                if (apptOrderType == ApptOrderExtensions.OrderType.其它平台预约.ToInt32().ToString())
                {
                  
                }

                // 直接挂号
                if (apptOrderType == ApptOrderExtensions.OrderType.直接挂号.ToInt32().ToString())
                {
                // 取号中
                //order.OrderStatus = ApptOrderExtensions.OrderStatus.取号中.ToInt32();
                //ctx.SaveChanges();
                using (var _ctx = new HzfyWeiXinEntities())
                {
                    SqlParameter[] para =
                    {
                                new SqlParameter("@OrderStatus", ApptOrderExtensions.OrderStatus.取号中.ToInt32()),
                                new SqlParameter("@OrderId", order.Id),
                            };
                    _ctx.Database.ExecuteSqlCommand(
                        "Update ApptOrder set OrderStatus= @OrderStatus where Id=@OrderId", para);
                }
                //执行取号操作
                var directRegRequest = new Request4ExeResSourceRegister();
                    directRegRequest.OrderId = order.OrderNo;
                    directRegRequest.OrderType = "1";
                    directRegRequest.PayType = "2";
                    directRegRequest.CardNo = order.CardNo;
                    directRegRequest.PayCount = order.SumFee.ToString();
                    directRegRequest.TransNo = order.WxTransactionId;
                    directRegRequest.TransTime = order.PayTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");
                    directRegRequest.DeptId = order.DeptId;
                    directRegRequest.DoctorId = order.DoctorId;
                    directRegRequest.RegDate = order.RegDate;
                    directRegRequest.TimeSlice = order.TimeSlice;
                    directRegRequest.RegType = order.RegType;
                    directRegRequest.StartTime = order.StartTime;
                    directRegRequest.EndTime = order.EndTime;
                    directRegRequest.Fee = order.Fee.GetValueOrDefault().ToString();
                    directRegRequest.TreatFee = order.TreatFee.GetValueOrDefault().ToString();
                    directRegRequest.OtherFee = order.OtherFee.GetValueOrDefault().ToString();
                    directRegRequest.RegNo = order.RegNo ?? "";

                    Response4ExeResSourceRegister directRegResponse;

                    try
                    {
                        var httpClient = InHttpClient.GetClient();
                        var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/GetRegInfo", directRegRequest).Result;
                        responseMsg.EnsureSuccessStatusCode();
                        directRegResponse = responseMsg.Content.ReadAsAsync<Response4ExeResSourceRegister>().Result;
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat("调用院内直接取号Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                        // RMQ 执行取号结果查询
                        var pickupingChkProducer = new OrderPickupingChkProducer();
                        pickupingChkProducer.Publish(new OrderPickupingChkMsg
                        {
                            OrderType = Rmq.Center.OrderType.挂号订单,
                            OrderId = order.Id
                        }, 5 * 60 * 1000);

                        return new ConsumedResult
                        {
                            Ack = true
                        };
                    }

                    if (directRegResponse.ResultCode != "0")
                    {
                    // 取号失败
                    //order.OrderStatus = ApptOrderExtensions.OrderStatus.取号失败.ToInt32();
                    //order.Remark = directRegResponse.ResultDesc;
                    //ctx.SaveChanges();
                    using (var _ctx = new HzfyWeiXinEntities())
                    {
                        SqlParameter[] para =
                        {
                                new SqlParameter("@OrderStatus", ApptOrderExtensions.OrderStatus.取号失败.ToInt32()),
                                new SqlParameter("@Remark", directRegResponse.ResultDesc),
                                new SqlParameter("@OrderId", order.Id),
                            };
                        _ctx.Database.ExecuteSqlCommand(
                            "Update ApptOrder set OrderStatus= @OrderStatus,Remark=@Remark where Id=@OrderId", para);
                    }

                    // RMQ 发送用户挂号失败通知
                    var msgProducer = new UserMessageProducer();
                        msgProducer.Publish(new UserMessageMsg
                        {
                            Type = UserMessageType.挂号失败通知,
                            OrderId = order.Id
                        });

                        // RMQ 执行退费操作
                        if (order.SumFee > 0)
                        {
                            var refundingProducer = new OrderRefundingPickupFailedProducer();
                            refundingProducer.Publish(new OrderRefundingPickupFailedMsg
                            {
                                OrderType = OrderType.挂号订单,
                                OrderId = order.Id
                            });
                        }
                    }
                    else
                    {
                    // 取号成功
                    //order.OrderStatus = ApptOrderExtensions.OrderStatus.取号成功.ToInt32();
                    //order.RegNo = directRegResponse.RegNo;
                    //order.SuggestBeginTime = directRegResponse.BeginTime;
                    //order.SuggestEndTime = directRegResponse.EndTime;
                    //order.Location = directRegResponse.Address;
                    //order.VisitNo = directRegResponse.VisitNo;

                    //order.FetchTime = DateTime.Now;
                    //ctx.SaveChanges(); RegNo = @RegNo,
                    using (var ctx = new HzfyWeiXinEntities())
                    {
                        var para = new SqlParameter[]
                        {
                            new SqlParameter("@OrderStatus", ApptOrderExtensions.OrderStatus.取号成功.ToInt32()),
                            new SqlParameter("@RegNo", directRegResponse.RegInfo.RegNo),
                            new SqlParameter("@SuggestBeginTime", directRegResponse.RegInfo.StartTime),
                            new SqlParameter("@SuggestEndTime", directRegResponse.RegInfo.EndTime),
                            new SqlParameter("@Location", directRegResponse.RegInfo.Address),
                            new SqlParameter("@VisitNo", directRegResponse.RegInfo.VisitNo),
                            new SqlParameter("@FetchTime", DateTime.Now),
                            new SqlParameter("@OrderId", order.Id)
                        };
                        ctx.Database.ExecuteSqlCommand("Update ApptOrder set OrderStatus= @OrderStatus," +
                                                       "RegNo = @RegNo,SuggestBeginTime=@SuggestBeginTime," +
                                                       "SuggestEndTime=@SuggestEndTime,Location=@Location,VisitNo=@VisitNo," +
                                                       "FetchTime=@FetchTime where Id=@OrderId", para);
                    }
                    // RMQ 发送用户挂号成功通知
                    var messageProducer = new UserMessageProducer();
                        messageProducer.Publish(new UserMessageMsg
                        {
                            Type = UserMessageType.挂号成功通知,
                            OrderId = order.Id
                        });

                        // RMQ 发送发货通知
                        if (order.SumFee > 0)
                        {
                            using (var ctx = new HzfyWeiXinEntities())
                            {
                                var wxuser = ctx.WxUser.FirstOrDefault(x => x.Id == order.WxUserId);
                                if (wxuser != null)
                                {
                                    //TenpayV2Helper.DoDeliverNotify(wxuser.OpenId, order.WxTransactionId,
                                    //"AP" + order.OrderNo, "1", "");
                                    WeixinPayV3Helper.DoDeliveryNotify(wxuser.OpenId, order.WxTransactionId,
                                        "AP" + order.OrderNo,
                                        ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000)/10000000)
                                            .ToString(), "1", "");
                                }
                            }
                        }
                    }

                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }
            

            return new ConsumedResult
            {
                Ack = true
            };
        }

        private ConsumedResult ProcessBillOrder(int orderId, WrapperChannel channel)
        {
            using (var ctx = new HzfyWeiXinEntities())
            {
                var order = ctx.BillOrder.FirstOrDefault(x => x.Id == orderId);
                if (order == null)
                {
                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }

                // 缴费中
                order.OrderStatus = BillOrderExtensions.OrderStatus.缴费中.ToInt32();
                ctx.SaveChanges();


                // 自费缴费
                var personPayRequest = new Request4ExePrescriptionPay();
                //执行缴费操作
                personPayRequest.OrderNo = order.OrderNo;
                personPayRequest.PrescNo = order.ClinicNo;
                personPayRequest.CardNo = order.CardNo;
                personPayRequest.SumFee = ("0" + order.PrescMoney).ToDecimalOrDefault().ToString("F4");
                personPayRequest.TransNo = order.WxTransactionId;
                personPayRequest.TransTime = order.PayTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");

                ////处方单列表
                //var prescriptions = ctx.BillOrderPrescriptions.Where(x => x.BillId == order.Id);
                //List<Request4ExePrescriptionPaySubPrescInfo> prescList = new List<Request4ExePrescriptionPaySubPrescInfo>();
                //foreach (var prescription in prescriptions)
                //{
                //    var prescInfo = new Request4ExePrescriptionPaySubPrescInfo();
                //    prescInfo.PrescMoney = ("0" + prescription.PrescMoney).ToDecimalOrDefault().ToString("F4");
                //    prescInfo.PrescNo = prescription.PrescNo;
                //    prescList.Add(prescInfo);
                //}
                //personPayRequest.PrescList = prescList;

                Response4ExePrescriptionPay personPayResponse;
                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/ExePrescriptionPay", personPayRequest).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    personPayResponse = responseMsg.Content.ReadAsAsync<Response4ExePrescriptionPay>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内缴费Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                    // RMQ 执行缴费状态结果查询
                    var pickupingChkProducer = new OrderPickupingChkProducer();
                    pickupingChkProducer.Publish(new OrderPickupingChkMsg
                    {
                        OrderType = Rmq.Center.OrderType.门诊缴费订单,
                        OrderId = order.Id
                    }, 5 * 60 * 1000);

                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }

                if (personPayResponse.ResultCode != "0")
                {
                    // RMQ 执行缴费状态结果查询
                    var pickupingChkProducer = new OrderPickupingChkProducer();
                    pickupingChkProducer.Publish(new OrderPickupingChkMsg
                    {
                        OrderType = Rmq.Center.OrderType.门诊缴费订单,
                        OrderId = order.Id
                    }, 5 * 60 * 1000);
                    //// 缴费失败
                    //order.OrderStatus = BillOrderExtensions.OrderStatus.缴费失败.ToInt32();
                    //order.Remark = personPayResponse.ResultDesc;
                    //ctx.SaveChanges();

                    //// RMQ 发起缴费失败通知
                    //var messageProducer = new UserMessageProducer();
                    //messageProducer.Publish(new UserMessageMsg
                    //{
                    //    OrderId = order.Id,
                    //    Type = UserMessageType.缴费失败通知
                    //});

                    //// RMQ 发起退款
                    //var refundingProducer = new OrderRefundingPickupFailedProducer();
                    //refundingProducer.Publish(new OrderRefundingPickupFailedMsg
                    //{
                    //    OrderType = OrderType.门诊缴费订单,
                    //    OrderId = order.Id
                    //});

                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }
                else
                {
                    // 缴费成功
                    order.OrderStatus = BillOrderExtensions.OrderStatus.缴费成功.ToInt32();

                    foreach (var disWin in personPayResponse.DisWinList)
                    {
                        var newBillOrderDisWin = new BillOrderDisWin
                        {
                            BillOrderId = order.Id,
                            DisWin = disWin.DisWin,
                            DisWinAdd = disWin.DisWinAdd,
                           // RcptNo = disWin.RcptNo,
                            VisitNo = disWin.VisitNo
                        };
                        ctx.BillOrderDisWin.Add(newBillOrderDisWin);
                    }

                    order.Remark = personPayResponse.ResultDesc;
                    order.FetchTime = DateTime.Now;
                    ctx.SaveChanges();

                    // RMQ 发起缴费成功通知
                    var messageProducer = new UserMessageProducer();
                    messageProducer.Publish(new UserMessageMsg
                    {
                        OrderId = order.Id,
                        Type = UserMessageType.缴费成功通知
                    });
                    var wxuser = ctx.WxUser.FirstOrDefault(x => x.Id == order.WxUserId);
                    if (wxuser != null)
                    {
                        // RMQ 发送发货通知
                        //TenpayV2Helper.DoDeliverNotify(wxuser.OpenId, order.WxTransactionId,
                        //    "BL" + order.OrderNo, "1", "");
                        WeixinPayV3Helper.DoDeliveryNotify(wxuser.OpenId, order.WxTransactionId,
                       "BL" + order.OrderNo, ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000)
                                        .ToString(), "1", "");
                    }
                }
            }
           

            return new ConsumedResult
            {
                Ack = true
            };
        }

        public class OrderSummary
        {
            public string OrderNo { get; set; }
            public string OrderType { get; set; }
            public int Id { get; set; }
            public decimal? SumFee { get; set; }
            public long? WxUserId { get; set; }
            public string WxTransactionId { get; set; }
            public DateTime? PayTime { get; set; }
            public string CardNo { get; set; }
            public int OrderStatus { get; set; }
            public string DeptName { get; set; }
            public string DoctorName { get; set; }
            public string DeptId { get; set; }
            public string RegDate { get; set; }
            public string TimeSlice { get; set; }
            public string RegType { get; set; }
            public decimal? TreatFee { get; set; }
            public decimal? Fee { get; set; }
            public string RegNo { get; set; }
            public string StartTime { get; set; }
            public string EndTime { get; set; }
            public decimal? OtherFee { get; set; }
            public string DoctorId { get; set; }
        }
    }
}